$(document).ready(function () {
    var viewer, viewer2d;
   
    var config = {
        extensions: [
            "Autodesk.Viewing.ZoomWindow",
            "Autodesk.AEC.Minimap3DExtension",
            "Autodesk.AEC.LevelsExtension",
            'Autodesk.DocumentBrowser',
        ],
        disabledExtensions: {
            measure: false,
            section: false,
        },
        memory: {
            limit: 32 * 1024    //32 GB
        }
    };

    var options = {
        env: 'Local',
        offline: 'true',
        useADP: false,
        offlineResourcePrefix: location.href.substring(0, location.href.lastIndexOf('/'))
    };
    var documentId = decodeURIComponent(options.offlineResourcePrefix + "/3d.svf");//.f2d 格式
    Autodesk.Viewing.Initializer(options, function () {
        show3dviewer();
        show2dviewer();
    });
    function show3dviewer() {
        var myViewerDiv = document.getElementById('forgeViewer3D');
        
        viewer = new Autodesk.Viewing.Private.GuiViewer3D(myViewerDiv, config);
        viewer.start(documentId, { isAEC: true }, onSuccess, onFailure);
        console.log(viewer,'里面都有啥？---------------------');
        //双击 放大构建 开始
        viewer.addEventListener(Autodesk.Viewing.GEOMETRY_LOADED_EVENT, function (event) { setTimeout(() => { 
            viewer.setViewCube("right"); }, 1000); 
        })
        //双击 放大构建 结束

        // viewer.addEventListener(Autodesk.Viewing.AGGREGATE_SELECTION_CHANGED_EVENT, function (event) {
        //     if (event.selections && (db3d == null || db3d != event.selections[0].dbIdArray[0])) {
        //         console.log("click3d", event.selections[0].dbIdArray);
        //         document.getElementById('ceng').style.display='block'
        //         db3d = event.selections[0].dbIdArray[0];
        //         viewer2d.select(event.selections[0].dbIdArray)
        //     }
        //     // presets_cams = NOP_VIEWER.model.getData().cameras
        //     // NOP_VIEWER.impl.setViewFromCamera(presets_cams[index]);
        // })
        
        // //在模型加载完成后改变模型视角 开始
        //     viewer.addEventListener( Autodesk.Viewing.GEOMETRY_LOADED_EVENT, function (event) {   
        //         setTimeout(function() {
        //             viewer.setViewCube('[front,top,left]'); },100)}//顺序为前后、上下、左右,根据自己需要尽心变换
        //     )     
        // //在模型加载完成后改变模型视角 开始
        viewer.registerContextMenuCallback('MyChangingColorMenuItems', ( menu, status ) => {
            if( status.hasSelected ) {
                menu.push({
                    title: 'Override color of selected elements to red',
                    target: () => {
                        const selSet = this.viewer.getSelection();
                        this.viewer.clearSelection();
         
                        const color = new THREE.Vector4( 255 / 255, 0, 0, 1 );
                        for( let i = 0; i < selSet.length; i++ ) {
                            this.viewer.setThemingColor( selSet[i], color );
                        }
                    }
                });
            } else {
                menu.push(
                    {
                        title: 'Clear overridden corlor1',
                        target: () => {
                            alert('11111111');
                            this.viewer.clearThemingColors();
                        }
                    },
                    {
                        title: 'Clear overridden corlor2',
                        target: () => {
                            this.viewer.clearThemingColors();
                        }
                    },
                    {
                        title: 'Clear overridden corlor3',
                        target: () => {
                            this.viewer.clearThemingColors();
                        }
                    }
                );
            }
        });
        viewer.setBackgroundColor( 0, 0, 60, 0, 157, 191);//改变加载时最初的背景颜色
        viewer.loadExtension('ToolbarExtension');//添加新按钮(红蓝)
        // 将信息更新到相机上       
        // viewer.autocam.goToView(defaultViewer);

        //在模型加载完成后改变模型视角
        // viewer.addEventListener( Autodesk.Viewing.GEOMETRY_LOADED_EVENT, function (event) {   
        //     setTimeout(function() {
        //         viewer.setViewCube('[front,top,left]'); },100)}//顺序为前后、上下、左右,根据自己需要尽心变换
        // )
    //加载页面视角 开始    "[front/back], [top/bottom], [left/right]"

        // setTimeout(function() {
        //     viewer.loadExtension('Autodesk.ViewCubeUi') .then(ext=>ext.setViewCube('[front,top,left]'))},1000
        // )
    //加载页面视角 结束
    }
    //加载页面视角 开始
        // viewcuiext = viewer.getExtension('Autodesk.ViewCubeUi')
        // viewcuiext.setViewCube(display);
    //加载页面视角 结束

    // 添加工具栏 开始
      function ToolbarExtension(viewer, options) {
        Autodesk.Viewing.Extension.call(this, viewer, options);
      }
      
      ToolbarExtension.prototype = Object.create(Autodesk.Viewing.Extension.prototype);
      ToolbarExtension.prototype.constructor = ToolbarExtension;
      
      ToolbarExtension.prototype.load = function() {

        if (this.viewer.toolbar) {
          // Toolbar is already available, create the UI
          this.createUI();
        } else {
          // Toolbar hasn't been created yet, wait until we get notification of its creation
          this.onToolbarCreatedBinded = this.onToolbarCreated.bind(this);
          this.viewer.addEventListener(Autodesk.Viewing.TOOLBAR_CREATED_EVENT, this.onToolbarCreatedBinded);
        }
      
        return true;
      };
      
      ToolbarExtension.prototype.onToolbarCreated = function() {
        this.viewer.removeEventListener(Autodesk.Viewing.TOOLBAR_CREATED_EVENT, this.onToolbarCreatedBinded);
        this.onToolbarCreatedBinded = null;
        this.createUI();
      };
      
      ToolbarExtension.prototype.createUI = function() {
        // alert('TODO: Create Toolbar!');
        var viewer = this.viewer;

        // Button 1
        var button1 = new Autodesk.Viewing.UI.Button('my-view-front-button');
        button1.onClick = function(e) {
            // viewer.setViewCube('front');
            // viewer.getState();
        };
        button1.addClass('my-view-front-button');
        button1.setToolTip('View front');
      
        // Button 2
        var button2 = new Autodesk.Viewing.UI.Button('my-view-back-button');
        button2.onClick = function(e) {
            // viewer.setViewCube('back');
            // viewer.getState();
        };
        button2.addClass('my-view-back-button');
        button2.setToolTip('View Back');
      
        // SubToolbar
        this.subToolbar = new Autodesk.Viewing.UI.ControlGroup('my-custom-view-toolbar');
        this.subToolbar.addControl(button1);
        this.subToolbar.addControl(button2);
      
        viewer.toolbar.addControl(this.subToolbar);
      };
      
      ToolbarExtension.prototype.unload = function() {
        // nothing yet
      };
      
      Autodesk.Viewing.theExtensionManager.registerExtension('ToolbarExtension', ToolbarExtension);
      // 添加工具栏 结束
    //初始化视角 开始
       const eye = viewer.navigation.getEyeVector();
       const newPosition = new THREE.Vector3(-808.8144114263626, -480.3273446852653, 566.7830755532873);
       const target = eye.add( newPosition );
       const up=new THREE.Vector3(0.3887726104595453,0.12839765943236225,0.9123430815262217);
       const worldUp=new THREE.Vector3(0,0,1);
       const center=new THREE.Vector3(-446.59100073377203,-254.7583215368543,236.66966636633654);
       const pivot=new THREE.Vector3(-464.94482906148437,-217.88815652611004,230.05122957846686);
       const defaultViewer ={
           position: newPosition.clone(),                   
           up: up.clone(),
           center: center.clone(),                          
           pivot: pivot.clone(),                           
           fov: 153.130101602940826,
           worldUp: worldUp.clone(),
           isOrtho: false
       };        
         

    //初始化视角 结束
    



    function show2dviewer() {
        var myViewerDiv = document.getElementById('forgeViewer2D');
        viewer2d = new Autodesk.Viewing.Private.GuiViewer3D(myViewerDiv);
        viewer2d.start(documentId, { isAEC: true }, onSuccess, onFailure);
        viewer2d.addEventListener(Autodesk.Viewing.AGGREGATE_SELECTION_CHANGED_EVENT, function (event) {
            if (event.selections && (db2d == null || db2d != event.selections[0].dbIdArray[0])) {
                // console.log("click2d", event.selections[0].dbIdArray);
                db2d = event.selections[0].dbIdArray[0];
                viewer.select(event.selections[0].dbIdArray);
            }
        })
    }

    var db2d, db3d;

    //获取2d图纸，取其中一个node显示
    function getManifestList(doc) {
        const filterGeom = (geom) => ['2d'].indexOf(geom.data.role) !== -1;
        const geometries = doc.getRoot().search({ type: 'geometry' }).filter(filterGeom);
        console.log("geometries", geometries);
        var guid = "6d3acd40-53b7-41b4-9d96-72e9eaf4bc89-0005d699";
        //获取节点
        var viewables = (guid ? doc.getRoot().findByGuid(guid) : doc.getRoot().getDefaultGeometry());
        viewer2d.loadDocumentNode(doc, viewables).then(i => {

        });

    }

    function onSuccess(document) {
        var documentPath = decodeURIComponent(options.offlineResourcePrefix + "/manifest-model.json");
        
        //加载manifest
        Autodesk.Viewing.Document.load(documentPath, (doc) => {
            if (viewer2d) {
                getManifestList(doc);
            }
            if (viewer) {
                doc.downloadAecModelData();
                var viewable = doc.getRoot().getDefaultGeometry();
                var options = {};
                //小地图
                viewer.loadDocumentNode(doc, viewable, options).then(i => {
                    viewer.loadExtension('Autodesk.AEC.Minimap3DExtension');
                });

            }
        });
    }

    function onFailure(viewerErrorCode, viewerErrorMsg) {
        console.error('onDocumentLoadFailure() - errorCode:' + viewerErrorCode + '\n- errorMessage:' + viewerErrorMsg);
    }
});